package com.itheima.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.Key;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 生成token
 * 解析token
 */
public class TokenUtil {

    //设置token标签
    private static final String BEARER = "bearer_";
    //设置redis中token的键标签
    private static final String LOGIN = "LOGIN_";

    private static Logger logger = LoggerFactory.getLogger(TokenUtil.class);
    // 使用HS256算法和Secret:example生成signKey
    private static Key getKeyInstance() {
        // We will sign our JavaWebToken with our ApiKey secret
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("ApiKey");//ApiKey可自定义，是秘钥
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    // 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
    public static String createJavaWebToken(Map<String, Object> claims) {
        logger.info("begin create token");
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
    }

    // 解析Token，同时也能验证Token，当验证失败返回null
    public static Map<String, Object> parserJavaWebToken(String jwt) {
        try {
            Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwt).getBody();
            return jwtClaims;
        } catch (Exception e) {
            logger.error("parse token failed");
            return null;
        }
    }

    public static Map<String,Object> getUserInfo(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("Authorization".equals(name)){
                String token = cookie.getValue();
                String replace = token.replace(BEARER, "");
                return parserJavaWebToken(replace);
            }
        }
        return null;
    }
}
